package com.gezi.admin.module.sys.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gezi.admin.aop.log.Logging;
import com.gezi.admin.config.exception.type.ApiException;
import com.gezi.admin.module.sys.menu.SysMenuService;
import com.gezi.admin.module.sys.role.SysRoleEntity;
import com.gezi.admin.module.sys.role.SysRoleService;
import com.gezi.admin.module.sys.user.model.*;
import com.gezi.admin.module.sys.user.model.*;
import com.gezi.admin.module.sys.user.role.SysUserRoleEntity;
import com.gezi.admin.module.sys.user.role.SysUserRoleService;
import com.gezi.admin.config.argument.RequestBodyParam;
import com.gezi.admin.module.config.BaseController;
import com.gezi.admin.module.config.utils.PageUtil;
import com.gezi.admin.module.config.utils.PageVo;
import com.gezi.admin.security.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 格子代码
 * @createDate 2024/2/10 09:00
 * @contact 1424529270@qq.com
 */
@Slf4j
@Api(tags = "用户管理")
@RequestMapping("/api/sys/user")
@RestController
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @PreAuthorize("hasAuthority('sys:user:findAllByPage')")
    @ApiOperation("查询分页")
    @GetMapping("/findAllByPage")
    public Object findAllByPage(PageVo page, UserSearchAddOrEditModel searchModel) {
        Page<Map> pageData = sysUserService.findAllByPage(PageUtil.initMpPage(page),searchModel);
        for (Map record : pageData.getRecords()) {
            List<SysRoleEntity> roleEntityList = sysUserRoleService.getUserRole(record.get("id").toString());
            record.put("roleNameList",Arrays.asList());
            if(CollUtil.isNotEmpty(roleEntityList)){
                record.put("roleNameList",roleEntityList.stream().map(item->item.getName()).distinct().collect(Collectors.toList()));
            }
        }
        return pageData;
    }


    @Logging(tags = "系统用户管理",value = "添加")
    @PreAuthorize("hasAuthority('sys:user:add')")
    @ApiOperation("添加")
    @PostMapping("/add")
    public void saveUser(@RequestBody @Validated SysUserAddParamModel customAdmin) {
        SysUserEntity sysUser = sysUserService.checkSysUserUnique(customAdmin.getLoginName());
        if(!Objects.isNull(sysUser)){
            throw new ApiException("账号已存在");
        }
        sysUserService.add(customAdmin);
    }

    @Logging(tags = "系统用户管理",value = "修改")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    @ApiOperation("修改")
    @PostMapping("/edit")
    public void revampUser(@RequestBody @Validated SysUserEditParamModel customAdmin) {
        if (getUserId().equals(customAdmin.getId())) {
            throw new ApiException("不可修改自己");
        }
        SysUserEntity sysUser=sysUserService.checkSysUserUnique(customAdmin.getLoginName());
        if(sysUser != null && !customAdmin.getId().equals(sysUser.getId())){
            throw new ApiException("账号已存在，请刷新重试");
        }
        sysUserService.edit(customAdmin);
    }

    @Logging(tags = "系统用户管理",value = "删除")
    @PreAuthorize("hasAuthority('sys:user:delByIds')")
    @ApiOperation("删除")
    @DeleteMapping(value = "/delByIds/{ids}")
    public void delByIds(@PathVariable String[] ids) {
        if (Arrays.asList(ids).contains(SecurityUtil.getUserId())) {
            throw new ApiException("不可删除自己");
        }
        sysUserService.delByIds(ids);
    }

    @ApiOperation("查询个人信息")
    @GetMapping("/findProfile")
    public Object findProfile(){
        SysUserEntity sysUserEntity = sysUserService.getById(getUserId());
        Map map = MapUtil.builder().build();
        map.put("id",sysUserEntity.getId());
        map.put("nickName",sysUserEntity.getNickName());
        map.put("loginName",sysUserEntity.getLoginName());
        map.put("headUrl",sysUserEntity.getHeadUrl());
        map.put("phone",sysUserEntity.getPhone());
        map.put("email",sysUserEntity.getEmail());
        List<SysRoleEntity> roleList = sysUserRoleService.getUserRole(getUserId());
        map.put("roleNameList",roleList.stream().map(item->item.getName()).collect(Collectors.toList()));
        map.put("roleList",roleList.stream().map(item->item.getPermission()).collect(Collectors.toList()));
        List<String> permissionList = sysMenuService.findAllPerByUserId(getUserId());
        map.put("permissionList",permissionList);
        return map;
    }

    @Logging(tags = "系统用户管理",value = "修改个人信息")
    @ApiOperation("修改个人信息")
    @PostMapping("/edit/profile")
    public void editProfile(@RequestBody @Validated SysUserEditProfileParamModel paramModel) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if (!sysUser.getLoginName().equals(paramModel.getLoginName())) {
            SysUserEntity exist = sysUserService.findByLoginName(paramModel.getLoginName());
            if (!Objects.isNull(exist)) {
                throw new ApiException("账号已存在");
            }
        }
        sysUser.setLoginName(paramModel.getLoginName());
        sysUser.setNickName(paramModel.getNickName());
        sysUser.setPhone(paramModel.getPhone());
        sysUser.setHeadUrl(paramModel.getHeadUrl());
        sysUserService.saveOrUpdate(sysUser);
    }

    @Logging(tags = "系统用户管理",value = "用户重置密码")
    @ApiOperation("重置密码")
    @PreAuthorize("hasAuthority('sys:user:rePassword')")
    @PostMapping("/rePassword")
    public String rePassword(@RequestBody @Validated SysUserRePasswordParamModel paramModel) {
        SysUserEntity sysUser = sysUserService.getById(paramModel.getId());
        if (sysUser == null) {
            throw new ApiException("用户不存在，请稍后重试");
        }
        String salt = BCrypt.gensalt();
        String newPassword = "123456";
        sysUser.setPassword(BCrypt.hashpw(newPassword,salt));
        sysUser.setSalt(salt);
        sysUserService.saveOrUpdate(sysUser);

        return newPassword;
    }

    @Logging(tags = "系统用户管理",value = "用户修改密码")
    @ApiOperation("修改密码")
    @PostMapping("/edit/password")
    public void editPassword(@RequestBodyParam("oldPassword") String oldPassword,@RequestBodyParam("newPassword") String newPassword) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if (!sysUser.getPassword().equals(BCrypt.hashpw(oldPassword,sysUser.getSalt()))) {
            throw new ApiException("密码不正确");
        }
        String salt = BCrypt.gensalt();
        sysUser.setPassword(BCrypt.hashpw(newPassword,salt));
        sysUser.setSalt(salt);
        sysUserService.saveOrUpdate(sysUser);
    }

    @Logging(tags = "系统用户管理",value = "用户修改头像")
    @ApiOperation("修改头像")
    @PostMapping("/edit/avatar")
    public void editAvatar(@RequestBody CustomAdmin customAdmin) {
        SysUserEntity sysUser = sysUserService.getById(SecurityUtil.getUserId());
        if(sysUser == null){
            throw new ApiException("账号不存在，请刷新重试");
        }
        sysUser.setHeadUrl(customAdmin.getHeadUrl());
        sysUserService.saveOrUpdate(sysUser);
    }
}
